package com.yuanhua.sim.thread;

import com.yuanhua.core.utils.SpringUtils;
import com.yuanhua.sim.config.AppConfiguration;
import com.yuanhua.sim.netty.utils.ZookeeperUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * @author yuanhua
 */
@Slf4j
public class RegistryZK implements Runnable {

    private String ip;
    private int simServerPort;
    private int httpPort;

    private AppConfiguration appConfiguration;

    private ZookeeperUtil zookeeperUtil;

    public RegistryZK(String ip, int simServerPort, int httpPort) {
        this.ip = ip;
        this.simServerPort = simServerPort;
        this.httpPort = httpPort;
        this.appConfiguration = SpringUtils.getBean(AppConfiguration.class);
        this.zookeeperUtil = SpringUtils.getBean(ZookeeperUtil.class);
    }

    @Override
    public void run() {
        //创建父节点 持久化节点
        try {
            Stat rootNode = zookeeperUtil.isExistNode(appConfiguration.getZkRoot());
            if(rootNode == null) {
                zookeeperUtil.createNode(appConfiguration.getZkRoot(),1, null, CreateMode.PERSISTENT);
            }
            //是否将自己注册到zk
            if(appConfiguration.getZkSwitch()){
                String path = appConfiguration.getZkRoot() + "/ip-" + ip + ":" + simServerPort + ":" + httpPort;
                Stat existNode = zookeeperUtil.isExistNode(path);
                if (existNode == null){
                    zookeeperUtil.createNode(path, 1, null, CreateMode.EPHEMERAL);
                }
                //
                log.info("NettyServer注册到zookeeper成功！msg[{}]" + path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
